#include <string.h>
#include <stdlib.h>
#include "array_stack.h"

int astack_init(astack_t **s, int capacity, int size)
{
    if (NULL != *s) // 惩罚使用野指针初始化的人
        return -1;

    *s = malloc(sizeof(astack_t));
    if (NULL == *s)
        return -1;
    
    (*s)->base = calloc(capacity, size); // calloc 会初始化为 0
    if (NULL == (*s)->base) {
        free(*s);
        *s = NULL;
        return -1;
    }

    (*s)->capacity = capacity;
    (*s)->top = 0;
    (*s)->size = size;

    return 0;
}

int astack_empty(astack_t *s)
{
    return s->top == 0;
}

int astack_full(astack_t *s)
{
    return s->top == s->capacity;
}

int astack_push(astack_t *s, const void *data)
{
    if (astack_full(s))
        return -1;

    memcpy((char *)(s->base) + s->top * s->size, data, s->size);

    s->top++;

    return 0;
}

int astack_pop(astack_t *s, void *elem)
{
    if (astack_empty(s))
        return -1;
    
    s->top--;
    memcpy(elem, (char *)(s->base) + s->top * s->size, s->size);
    memset((char *)(s->base) + s->top * s->size, '\0', s->size);

    return 0;
}

void astack_destroy(astack_t **s)
{
    free((*s)->base);
    (*s)->base = NULL;
    free(*s);
    *s = NULL;
}

